package com.cassio.stores.dao;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cassio.common.entity.City;
import com.cassio.common.entity.State;
import com.cassio.stores.util.DAOConstants;
import com.cassio.stores.util.DBHelper;

public class CityDAO {
	
	public static List<City> findAllByState(State state) {
		SQLiteDatabase db = DBHelper.getInstance().getReadableDatabase();

		String[] columns = { City.COL_ID, City.COL_NAME };
		String[] selArgs = { state.getId().toString() };
		Cursor cursor = db.query(City.TABLE_NAME, columns, City.COL_STATE_FK + DAOConstants.EQUALS, selArgs, null, null, null);

		List<City> cities = new ArrayList<City>();
		if (cursor.moveToFirst())
			do {
				City city = new City();
				city.setId(cursor.getInt(0));
				city.setName(cursor.getString(1));
				city.setState(state);
				cities.add(city);
			} while (cursor.moveToNext());

		cursor.close();
		cursor.deactivate();
		db.close();
		return cities;
	}
	
	public static City find(Integer cityId) {
		SQLiteDatabase db = DBHelper.getInstance().getReadableDatabase();
		
		String[] columns = { City.COL_ID, City.COL_NAME, City.COL_STATE_FK };
		String[] selArgs = { cityId.toString() };
		Cursor cursor = db.query(City.TABLE_NAME, columns, City.COL_ID + DAOConstants.EQUALS, selArgs, null, null, null);
		
		City city = null;
		if (cursor.moveToFirst())
			city = new City();
			city.setId(cursor.getInt(0));
			city.setName(cursor.getString(1));
			city.setState(StateDAO.find(cursor.getInt(2)));
		
		cursor.close();
		cursor.deactivate();
		db.close();
		return city;
	}

	public static City find(String cityName) {
		SQLiteDatabase db = DBHelper.getInstance().getReadableDatabase();
		
		String[] columns = { City.COL_ID, City.COL_NAME, City.COL_STATE_FK };
		String[] selArgs = { cityName };
		Cursor cursor = db.query(City.TABLE_NAME, columns, City.COL_NAME + DAOConstants.EQUALS, selArgs, null, null, null);
		
		City city = null;
		if (cursor.moveToFirst())
			city = new City();
			city.setId(cursor.getInt(0));
			city.setName(cursor.getString(1));
			city.setState(StateDAO.find(cursor.getInt(2)));
		
		cursor.close();
		cursor.deactivate();
		db.close();
		return city;
	}
}
